<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="120px">
    <el-form-item label="舌诊次数" prop="count">
      <el-input-number
        v-model="ruleForm.count"
        :min="1"
        :controls="false"
        style="width: 100%"
        :step-strictly="true"
      />
    </el-form-item>
    <el-form-item label="关联会员等级" prop="level">
      <el-select
        v-model="ruleForm.level"
        placeholder="请选择关联会员等级"
        :disabled="!!props.data.level"
      >
        <el-option
          v-for="item in availableLevels"
          :key="item.id"
          :label="item.name"
          :value="item.level"
          :disabled="isLevelUsed(item.level)"
        />
      </el-select>
      <div v-if="!!props.data.level" class="text-gray-400 text-sm mt-1">会员等级不可修改</div>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue'
import { getLevelList } from '@/api/member/level'
import { getBenefitsListTongue } from '@/api/member/benefits'
import { ElMessage } from 'element-plus'

const ruleForm = ref<any>({
  count: 1,
  level: undefined
})
const rules = ref<any>({
  count: [{ required: true, message: '请输入舌诊次数', trigger: 'blur' }],
  level: [{ required: true, message: '请选择关联会员等级', trigger: 'blur' }]
})
const ruleFormRef = ref<any>({})
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
})
const emit = defineEmits(['success'])
const levelList = ref<any[]>([])
const tongueRights = ref<any[]>([])

// 获取会员等级列表
const getLevelListData = async () => {
  const data = await getLevelList({})
  levelList.value = data
}

// 获取现有舌诊权益列表
const getTongueRightsList = async () => {
  try {
    // 强制清空现有数据，确保不会使用缓存数据
    tongueRights.value = []

    // 获取最新数据
    const response = await getBenefitsListTongue()
    console.log('刷新舌诊权益列表:', response)

    // 更新数据
    tongueRights.value = Array.isArray(response) ? response : response.data || []

    // 返回最新数据以便进一步处理
    return tongueRights.value
  } catch (error) {
    console.error('加载舌诊权益列表失败:', error)
    tongueRights.value = []
    return []
  }
}

// 检查会员等级是否已被使用
const isLevelUsed = (level: number): boolean => {
  // 如果是编辑状态，排除当前编辑项
  if (props.data.level === level) {
    return false
  }

  // 检查是否已存在该会员等级的舌诊权益
  const isUsed = tongueRights.value.some((item) => item.level === level)

  // 添加调试信息
  if (isUsed) {
    console.log(`会员等级 ${level} 已被使用`)
  }

  return isUsed
}

// 可用的会员等级列表
const availableLevels = computed(() => {
  return levelList.value
})

// 监听props.data变化，确保每次编辑都能正确回显
watch(
  () => props.data,
  (newVal) => {
    console.log('props.data变化:', newVal)
    if (newVal) {
      // 重置表单数据
      ruleForm.value = {
        count: newVal.count || 1,
        level: newVal.level || undefined
      }
      console.log('表单数据已更新:', ruleForm.value)
    }
  },
  { deep: true, immediate: true }
)

// 监听弹窗显示状态，每次显示时刷新数据
const visible = computed(() => {
  // 根据data中是否有值来判断弹窗是否显示
  const isVisible = Object.keys(props.data).length > 0

  // 如果弹窗刚刚显示，则刷新数据
  if (isVisible) {
    // 使用nextTick确保在DOM更新后执行
    nextTick(() => {
      getTongueRightsList()
    })
  }

  return isVisible
})

// 组件挂载时获取会员等级列表和舌诊权益列表
onMounted(() => {
  getLevelListData()
  getTongueRightsList()
})

// 表单提交前验证
const validateForm = async () => {
  // 检查是否选择了已被使用的会员等级
  if (isLevelUsed(ruleForm.value.level)) {
    return Promise.reject('该会员等级已被其他舌诊权益使用，请选择其他会员等级')
  }
  return Promise.resolve()
}

// 提交表单方法
const submitForm = () => {
  ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 额外验证
        await validateForm()

        const data = {
          ...props.data,
          ...ruleForm.value
        }
        emit('success', data)
      } catch (error) {
        ElMessage.error({
          message: error as string,
          type: 'error'
        })
      }
    }
  })
}

// 暴露submitForm方法给父组件调用
defineExpose({
  submitForm,
  getTongueRightsList
})
</script>
<style scoped>
.text-gray-400 {
  color: #9ca3af;
}
.text-sm {
  font-size: 0.875rem;
}
.mt-1 {
  margin-top: 0.25rem;
}
</style>
